//index.js
// 引入SDK核心类
var QQMapWX = require('../../dist/js/qqmap-wx-jssdk.js');
var qqmapsdk;
//获取应用实例
const app = getApp()

Page({
  data: {
    address: '',
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'RSEBZ-6TY35-LRTID-Q3SSV-B2G72-PNF4B'
    });
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude,
            poi_options: "poi_options=address_format=short"
          },
          complete: function (res) {
            that.setData({
              address: res.result.address_component.city + res.result.address_component.district + res.result.address_component.street_number
            })
          }
        })
      }
    })
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  // 监听页面显示
  onShow: function () {
  
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  chooseLoc: function() {
    const that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log(res)
        that.setData({
          address: res.name
        })
      }
    })
  },
  scan: function () {
    wx.navigateTo({
      url: 'camera/camera',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  gotoSearch: function() {
    wx.navigateTo({
      url: 'search/search',
    })
  }
})
